<script>
import { ApiCreateOrder, ApiGetOrderStatus } from "@/http/api";
import { ElMessage } from "element-plus";
import QrcodeVue from "qrcode.vue";

export default {
  components: {
    QrcodeVue,
  },
  data() {
    return {
      title: "选择支付金额",
      qrTitle: "请使用支付宝扫码支付",
      visible: true,
      qrVisible: false,
      loading: false,
      amount: 0.0,
      qrURL: null,
      leftSeconds: 10 * 60,
      deviceWidth: "100%",
      redirect: null,
      orderName: null,
      orderNo: null,
    };
  },
  methods: {
    // 设置 amount
    setAmount(value) {
      this.amount = value;
    },

    // 查询订单状态
    getOrderStatus(orderNo) {
      this.orderInterval = setInterval(() => {
        ApiGetOrderStatus({ order_no: orderNo }).then((res) => {
          if (res.success) {
            if (res.data.is_paid) {
              ElMessage.success("支付成功!");
              // 清除信息
              this.resetValue();
            } else {
              this.leftSeconds -= 2;
            }
          } else {
            console.error("GetOrderStatusFailed", res);
            ElMessage.error("查询订单出错，请联系管理员~");
            this.resetValue();
          }
        });
      }, 2000);
    },
    // 重置状态
    resetValue() {
      clearInterval(this.orderInterval);
      this.leftSeconds = 600;
      this.qrURL = null;
      this.qrVisible = false;
      this.loading = false;
      // 参数重置
      // this.orderName = null;
      // this.redirect = null;
      // 重定向
      if (this.redirect) {
        window.location.href = this.redirect + `?order_no=${this.orderNo}`;
      }
      // this.orderNo = null;
    },
    // 创建订单，获取二维码
    getQRCode() {
      this.visible = false;
      this.qrVisible = true;
      this.loading = true;

      ApiCreateOrder({
        order_name: this.orderName || `web端充值￥${this.amount}元`,
        source: "alipay",
        amount: this.amount,
      })
        .then((res) => {
          if (res.success) {
            this.loading = false;
            this.qrURL = res.data.qrcode;
            this.orderNo = res.data.order_no;
            this.getOrderStatus(res.data.order_no);
          } else {
            ElMessage.error("请求出错，请稍后再试~");
            this.loading = false;
          }
        })
        .catch((err) => {
          this.loading = false;
          console.error(err);
          ElMessage.error("服务出错，请联系管理员~");
        });
    },
    // 调整设备尺寸
    setDeviceWidth() {
      let width = document.body.offsetWidth;
      if (width < 768) {
        this.deviceWidth = "95%";
      } else if (width < 992) {
        this.deviceWidth = "80%";
      } else if (width < 1200) {
        this.deviceWidth = "60%";
      } else if (width < 1500) {
        this.deviceWidth = "50%";
      } else {
        this.deviceWidth = "30%";
      }
    },
    // 判断参数中是否已经携带参数信息，如果是，直接调起支付接口
    goPayPageIf() {
      var redirect = this.getUrlParam("redirect");
      if (redirect) this.redirect = redirect;
      var title = this.getUrlParam("title");
      if (title) this.qrTitle = title;
      var orderName = this.getUrlParam("order_name");
      if (orderName) this.orderName = orderName;
      var amount = this.getUrlParam("amount");
      if (amount && redirect) {
        this.amount = parseInt(amount);
        this.getQRCode();
      }
    },
    // 获取请求参数
    getUrlParam(param) {
      // 获取由全部参数组成的字符串。
      let query = window.location.search.substring(1);
      // 分割参数，得到每一个参数字符串组成的数组。
      let vars = query.split("&");
      // 遍历数组，得到每一个参数字符串。
      for (let i = 0; i < vars.length; i++) {
        // 分割每一个参数字符串，得到参数名和参数值组成的数组。
        var pair = vars[i].split("=");
        // 如果参数名等于传入的param，则返回该值。
        if (pair[0] == param) {
          return decodeURI(pair[1]);
        }
      }
      // 若参数不存在，则返回false。
      return false;
    },
  },
  computed: {
    formattedLeftTime() {
      return `${parseInt(this.leftSeconds / 60)}分${this.leftSeconds % 60}秒`;
    },
    formattedAmountLabel() {
      return `￥${this.amount}元`;
    },
    stopInterval() {
      if (this.leftSeconds <= 0) {
        clearInterval(this.orderInterval);
      }
    },
  },
  mounted() {
    // 动态判断设备尺寸并调整样式
    this.setDeviceWidth();
    addEventListener("resize", () => {
      this.setDeviceWidth();
    });
    // 判断请求参数来决定调用行为
    this.goPayPageIf();
  },
};
</script>

<template>
  <body>
    <el-button type="primary" @click="visible = true"> 点击支付 </el-button>

    <!-- 选择金额信息模态框 -->
    <el-dialog
      v-model="visible"
      :title="title"
      :width="deviceWidth"
      align-center
      center
    >
      <el-row justify="center">
        <el-col :xs="8" :sm="4">
          <el-button type="primary" plain @click="setAmount(1)"
            >￥1元</el-button
          >
        </el-col>
        <el-col :xs="8" :sm="4">
          <el-button type="primary" plain @click="setAmount(5)"
            >￥5元</el-button
          >
        </el-col>
        <el-col :xs="8" :sm="4">
          <el-button type="primary" plain @click="setAmount(10)"
            >￥10元</el-button
          >
        </el-col>
        <el-col :xs="8" :sm="4">
          <el-button type="primary" plain @click="setAmount(20)"
            >￥20元</el-button
          >
        </el-col>
        <el-col :xs="8" :sm="4">
          <el-button type="primary" plain @click="setAmount(50)"
            >￥50元</el-button
          >
        </el-col>
        <el-col :xs="8" :sm="4">
          <el-button type="primary" plain @click="setAmount(100)"
            >￥100元</el-button
          >
        </el-col>
      </el-row>
      <el-row justify="center" style="margin-top: 50px">
        <el-input-number
          v-model="amount"
          :min="1"
          :max="100"
          :precision="2"
          :step="5"
        />
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="getQRCode"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 二维码模态框 -->
    <el-dialog
      :title="qrTitle"
      v-model="qrVisible"
      :width="deviceWidth"
      align-center
      center
      @close="resetValue"
    >
      <el-divider />
      <el-row justify="center">
        <el-space direction="vertical" alignment="flex-start">
          <el-alert
            v-if="qrVisible && !loading"
            :type="leftSeconds > 30 ? 'success' : 'warning'"
            :closable="false"
            >请在{{ formattedLeftTime }}之内完成支付~</el-alert
          >
          <el-skeleton style="width: 240px" :loading="loading" animated>
            <template #template>
              <el-skeleton-item
                variant="image"
                style="width: 240px; height: 240px"
              />
            </template>
            <template #default>
              <el-card :body-style="{ padding: '0px', marginBottom: '1px' }">
                <QrcodeVue
                  :value="qrURL"
                  :size="200"
                  level="H"
                  v-if="qrVisible && !loading && qrURL"
                />
              </el-card>
            </template>
          </el-skeleton>
        </el-space>
      </el-row>
      <el-row justify="center">
        <el-tag class="ml-2" size="large" type="danger">{{
          formattedAmountLabel
        }}</el-tag>
      </el-row>
      <el-divider />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetValue">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </body>
</template>
